package client

import (
	"encoding/json"
	"fmt"
	"gin-epg/internal/app/client/utils"
	"gin-epg/internal/app/dao"
	"time"

	"github.com/go-resty/resty/v2"
	"github.com/spf13/cast"
)

// 频道列表url http://10.255.0.110/mgtv_hndx/EPGV2/GetChannelList?OutputType=json&Version=HNDX.0.0_Release_HW_4K&CategoryId=1000&MediaAssetsId=live
// 组播版本对应1234端口
// 湖南电信芒果tv版
var mapHunanTelecomMgtv = map[string]string{
	"65e48b2e8e6a4f73824fbbb44762e4c6": "湖南卫视",
	// 更多键值对...
}

// HandleHunanTelecomMgtvCron 处理湖南电信芒果版节目单
func HandleHunanTelecomMgtvCron() error {
	dao.Logger.Infof("HandleHunanTelecomMgtvCron start")
	date := time.Now().Format("20060102")
	dao.Logger.Infof(date)
	source := "hunantelecommgtv"

	client := resty.New()

	for channelId, channelName := range mapHunanTelecomMgtv {
		dao.Logger.Infof("Processing channel: %s, Name: %s", channelId, channelName)

		// 构建完整URL
		url := fmt.Sprintf("http://10.255.0.110/mgtv_hndx/BasicIndex/GetPlaybill?AfterDay=3&TimeZone=8&OutputType=json&Version=YYS.4.5.19.266.2.HNDX.0.0_Release_HW_4K&VideoType=1&Mode=relative&VideoId=%s&BeforeDay=0", channelId)

		resp, err := client.R().
			SetHeaders(map[string]string{
				"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
			}).
			Get(url)

		if err != nil {
			dao.Logger.Errorf("Error fetching data for channel %s: %v", channelId, err)
			continue
		}

		var data map[string]interface{}
		if err := json.Unmarshal(resp.Body(), &data); err != nil {
			dao.Logger.Errorf("Error unmarshalling JSON for channel %s: %v", channelId, err)
			continue
		}

		if days, ok := data["day"].([]interface{}); ok {
			for _, dayData := range days {
				dayMap := dayData.(map[string]interface{})
				day := cast.ToString(dayMap["day"])

				if items, ok := dayMap["item"].([]interface{}); ok {
					for _, item := range items {
						itemMap := item.(map[string]interface{})
						startTimeStr := cast.ToString(itemMap["begin"])
						timeLen := cast.ToInt64(itemMap["time_len"])

						// 将时间字符串转换为Unix时间戳
						momentStartDate, err := parseTime(day, startTimeStr)
						if err != nil {
							dao.Logger.Errorf("Error parsing start time for channel %s: %v", channelId, err)
							continue
						}
						momentStopDate := momentStartDate.Add(time.Duration(timeLen) * time.Second)

						title := cast.ToString(itemMap["text"])
						desc := ""

						db := dao.SqlSession
						utils.HandleCrossDayRecord(db, momentStartDate, momentStopDate, title, desc, channelName, source)
					}
				}
			}
		}
	}
	return nil
}
